package com.negative.utils;

import java.io.BufferedInputStream;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;
import android.text.Html;
import com.negative.activities.NegativeApplication;
import com.negative.data.EventItem;
import com.negative.data.PurchaseData;
import com.negative.data.SettingsData;

public class IOHelper {

	private static String settingsFile = "Settings";
	private static String purchasesFile = "Data";
	private static String infoFileLocation = "https://docs.google.com/document/d/1qLylO3pSXWwd5sWK-RrvKCRg8x7PLkifhIhKgz33820/export?format=txt&id=1qLylO3pSXWwd5sWK-RrvKCRg8x7PLkifhIhKgz33820&token=AC4w5VhDUXlm7IGVOdNPb7knDIZIAlZZpA%3A1401543086324";
	private static String specialEventsFileLocation = "https://docs.google.com/document/d/1mJKvi3Uq90LF8JJR28ROVtqfIMzSAS-ozLUo41RyiQE/export?format=txt&id=1mJKvi3Uq90LF8JJR28ROVtqfIMzSAS-ozLUo41RyiQE&token=AC4w5VgPYXj46JUjOSeBAlSjX3G4ukM_rQ%3A1401612384820";
	private static String credFileLocation = "https://docs.google.com/document/d/1-7gGp104hTUW4O9ig8dKAES4x4NI3EMuA_r5PatY4qA/export?format=txt";
	private static String adsFileLocation = "https://docs.google.com/document/d/1uoArdWe00Kik0KhEERxiJfiaweQNb4p57BiF1fDfREQ/export?format=txt";

	public static ArrayList<PurchaseData> ReadPurchases(Context context)
			throws Exception {
		int attempt = 0;
		Exception exp = null;
		while (attempt < 5) {
			try {
				ArrayList<PurchaseData> purchases = new ArrayList<PurchaseData>();
				FileInputStream file = context.openFileInput(purchasesFile);
				ObjectInputStream object = new ObjectInputStream(file);

				PurchaseData p = (PurchaseData) object.readObject();
				while (p != null) {
					purchases.add(p);
					try {
						p = (PurchaseData) object.readObject();
					} catch (EOFException e) {
						break;
					}
				}

				object.close();
				file.close();

				return purchases;
			} catch (Exception e) {

				// Tamir: added this two lines for debug.
				if (e instanceof FileNotFoundException)
					return new ArrayList<PurchaseData>();
				attempt++;
				exp = e;
			}
		}
		throw exp;
	}

	public static void WritePurchases(Context context,
			ArrayList<PurchaseData> purchases) throws Exception {
		int attempt = 0;
		Exception exp = null;
		while (attempt < 5) {
			try {
				FileOutputStream file = context.openFileOutput(purchasesFile,
						Context.MODE_PRIVATE);
				ObjectOutputStream object = new ObjectOutputStream(file);

				for (PurchaseData purchaseData : purchases) {
					object.writeObject(purchaseData);
				}

				object.close();
				file.close();
				return;
			} catch (Exception e) {
				attempt++;
				exp = e;
			}
		}
		throw exp;
	}

	public static SettingsData ReadSettings(Context context) throws Exception {
		int attempt = 0;
		Exception exp = null;
		while (attempt < 5) {
			try {

				SettingsData settings = null;

				FileInputStream file = context.openFileInput(settingsFile);
				ObjectInputStream object = new ObjectInputStream(file);

				settings = (SettingsData) object.readObject();

				object.close();
				file.close();

				return settings;
			} catch (Exception e) {
				attempt++;
				exp = e;
			}
		}
		throw exp;
	}

	public static void WriteSettings(Context context, SettingsData settings)
			throws Exception {
		int attempt = 0;
		Exception exp = null;
		while (attempt < 5) {
			try {

				FileOutputStream file = context.openFileOutput(settingsFile,
						Context.MODE_PRIVATE);
				ObjectOutputStream object = new ObjectOutputStream(file);

				object.writeObject(settings);

				object.close();
				file.close();
			} catch (Exception e) {
				attempt++;
				exp = e;
			}
		}
		throw exp;
	}

	public static void getInfoFromGoogleDoc(final ArrayList<EventItem> events) {
		Thread t = new Thread() {
			public void run() {

				HttpClient client = new DefaultHttpClient();
				try {
					HttpResponse response = client.execute(new HttpGet(
							infoFileLocation));

					BufferedInputStream is = new BufferedInputStream(response
							.getEntity().getContent());
					ArrayList<Byte> bytes = new ArrayList<Byte>();
					byte[] b = new byte[1];
					while (is.read(b) > 0) {
						bytes.add(b[0]);
					}
					byte[] buffer = new byte[bytes.size()];
					for (int i = 0; i < bytes.size(); i++)
						buffer[i] = bytes.get(i);
					String s = new String(buffer, "UTF-8");
					if (s != null && !s.isEmpty() && s.length() > 0)
						s = s.substring(1);
					parseInfo(s);
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		};
		t.start();
	}

	public static void getCredFromGoogleDoc(final APIHelper api) {

		HttpClient client = new DefaultHttpClient();
		try {
			HttpResponse response = client
					.execute(new HttpGet(credFileLocation));

			BufferedInputStream is = new BufferedInputStream(response
					.getEntity().getContent());
			ArrayList<Byte> bytes = new ArrayList<Byte>();
			byte[] b = new byte[1];
			while (is.read(b) > 0) {
				bytes.add(b[0]);
			}
			byte[] buffer = new byte[bytes.size()];
			for (int i = 0; i < bytes.size(); i++)
				buffer[i] = bytes.get(i);
			String s = new String(buffer, "UTF-8");
			if (s != null && !s.isEmpty() && s.length() > 0)
				s = s.substring(1);
			parseCred(s, api);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void getSpecialEventsFromGoogleDoc(
			final ArrayList<EventItem> events, boolean runOnNewThred) {
		Thread t = new Thread() {
			public void run() {

				HttpClient client = new DefaultHttpClient();
				try {
					HttpResponse response = client.execute(new HttpGet(
							specialEventsFileLocation));

					BufferedInputStream is = new BufferedInputStream(response
							.getEntity().getContent());
					ArrayList<Byte> bytes = new ArrayList<Byte>();
					byte[] b = new byte[1];
					while (is.read(b) > 0) {
						bytes.add(b[0]);
					}
					byte[] buffer = new byte[bytes.size()];
					for (int i = 0; i < bytes.size(); i++)
						buffer[i] = bytes.get(i);
					String s = new String(buffer, "UTF-8");
					if (s != null && !s.isEmpty() && s.length() > 0)
						s = s.substring(1);
					parseSpecialEvents(s, events);
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		};
		if (runOnNewThred == true) {
			t.start();
		} else {
			t.run();
		}
	}

	public static void getAdsFromGoogleDoc(NegativeApplication app) {

		HttpClient client = new DefaultHttpClient();
		try {
			HttpResponse response = client
					.execute(new HttpGet(adsFileLocation));

			BufferedInputStream is = new BufferedInputStream(response
					.getEntity().getContent());
			ArrayList<Byte> bytes = new ArrayList<Byte>();
			byte[] b = new byte[1];
			while (is.read(b) > 0) {
				bytes.add(b[0]);
			}
			byte[] buffer = new byte[bytes.size()];
			for (int i = 0; i < bytes.size(); i++)
				buffer[i] = bytes.get(i);
			String s = new String(buffer, "UTF-8");
			if (s != null && !s.isEmpty() && s.length() > 0)
				s = s.substring(1);
			parseAds(s, app);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	private static void parseSpecialEvents(String info,
			ArrayList<EventItem> events) {
		String[] split = info.split("\r\n");
		for (String name : split) {
			if (name == null || name.isEmpty() || name.length() == 0)
				continue;
			for (EventItem event : events) {
				if (Html.fromHtml(event.getName()).toString().equals(name)) {
					event.setIsSpecial(true);
					break;
				}
			}
		}
	}

	private static void parseCred(String cred, APIHelper api) {
		String[] split = cred.split("\r\n");
		api.setCred(split[0], split[1], split[2]);
	}

	private static void parseInfo(String info) {

	}

	private static void parseAds(String s, NegativeApplication app) {
		ArrayList<String> urls = new ArrayList<String>();
		String[] split = s.split("\r\n");
		for (String string : split) {
			urls.add(string);
		}
		app.setAdUrls(urls);
	}
}
